const { getData, getDataIf, addData, deleteData, selectDataId, updataColedata, updatePasswordData } =require('../../model/user/index')
const jwt = require("jsonwebtoken");
const SECRET = "hello";
const getUser=(req,res)=>{
    getData().then(data=>{
        res.send(data)
    })
}
const createUser=async(req,res)=>{
    let sj = new Date()
    let createTime = sj.toLocaleString()
    let expireTime=(createTime.slice(0,4)-0+5)+createTime.slice(4)
    let user = await getData()
    let person
    if (user.length==0) {
        person = sj.getFullYear() + "" + (sj.getMonth() + 1) + sj.getDate()
    }else {
        person = sj.getFullYear() + "" + (sj.getMonth() + 1) + sj.getDate() + (user[user.length - 1].id + 1)
    }
    getDataIf(req.query).then(data=>{
        if (data.length==0) {
             addData({username:req.query.username,password:req.query.password,createTime,expireTime,person})
            res.send({msg:"添加成功"})
        }else{
            res.send({msg:"用户用已拥有"})
        }
    }).catch(err=>{
        res.send(err)
    })
}
const deleteUser=(req,res)=>{
    deleteData(req.query).then(data=>{
        res.send({msg:"删除成功"})
    })
}
const selectIfId=(req,res)=>{
    selectDataId(req.query).then(data=>{
        res.send(data)
    })
}
const updataCole=(req,res)=>{
    updataColedata(req.query).then(data=>{
        res.send({msg:"修改成功"})
    }).catch(err=>{
        res.send({msg:"修改失败"})
    })
}

const updataPassword=(req,res)=>{
    let username=jwt.verify(req.query.username.slice(1,-1),SECRET)
    getDataIf({username}).then(data=>{
        if (data[0].password === req.query.oldpassword){
            updatePasswordData([req.query.newpassword,username]).then(data => {
                res.send({ msg: "修改成功" })
            })
        }else {
            res.send({msg:"密码错误无法修改"})
        }
    })
}
module.exports={
    getUser,
    createUser,
    deleteUser,
    selectIfId,
    updataCole,
    updataPassword
}